<template>
  <div class="markdown-view-box">
    <link rel="stylesheet" href="./static/editor.md-master/css/editormd.min.css"/>
    <link rel="stylesheet" href="./static/editor.md-master/css/style.css"/>
    <link rel="stylesheet" href="./static/editor.md-master/css/editormd.preview.min.css"/>
    <div id="markdown-view">
      <textarea style="display: none;">{{doc.content}}</textarea>
    </div>
  </div>
</template>
<script>
  import scriptjs from 'scriptjs'
  import {defaultConfig} from '@/assets/conf/editor'

  export default {
    name:'markdownEdit',
    props: {
      viewId: {
        'type': String,
        'default': 'markdown-view'
      },
      config: { // 编辑器配置
        type: Object
      },
      initData: {
        'type': String
      },
      initDataDelay: {
        'type': Number, // 延迟初始化数据时间，单位毫秒
        'default': 0
      }
    },
    data: function () {
      return {
        doc: {},
        editor: null
      }
    },
    methods: {
      fetchScript: function (url) {
        return new Promise((resolve) => {
          scriptjs(url, () => {
            resolve()
          })
        })
      },
      getDoc: function () {
        return this.doc
      },
      getConfig: function () {
        return {...defaultConfig, ...this.config}
      },
      forceUpdate: function () {
        this.$forceUpdate()
      },
      initView: function () {
        (async () => {
          await this.fetchScript('./static/jquery.min.js')
          await this.fetchScript('./static/editor.md-master/lib/marked.min.js')
          await this.fetchScript('./static/editor.md-master/lib/prettify.min.js')
          await this.fetchScript('./static/editor.md-master/lib/raphael.min.js')
          await this.fetchScript('./static/editor.md-master/lib/underscore.min.js')
          await this.fetchScript('./static/editor.md-master/lib/sequence-diagram.min.js')
          await this.fetchScript('./static/editor.md-master/lib/flowchart.min.js')
          await this.fetchScript('./static/editor.md-master/lib/jquery.flowchart.min.js')
          await this.fetchScript('./static/editor.md-master/editormd.min.js')
          this.$nextTick(() => {
            var config = this.getConfig();
            console.info(config)
            this.editor = window.editormd(this.viewId, config)
          })
        })()
      },

      showContent(id) {
        let vm = this
        vm.$store.state.base.editor.isEditing = false
        let markdownViewDiv = document.getElementById('markdown-view')
        if (markdownViewDiv) {
          markdownViewDiv.innerHTML = '<textarea style="display: none;"></textarea>'
          vm.initView()
          markdownViewDiv.getElementsByTagName('textarea')[0].innerHTML = 'fdsfasfdsfsaf'
        }

      }
    },
    mounted: function () {
      let vm = this
      let docId = vm.$router.currentRoute.name
      vm.showContent(docId)
    }
  }
</script>
